package com.peoit.honeycomb.application.impl;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.peoit.honeycomb.application.CommentsApplication;
import com.peoit.honeycomb.domain.Comments;
import com.peoit.honeycomb.domain.HoneycombProject;
import com.peoit.honeycomb.domain.User;
import com.peoit.honeycomb.domain.exception.ProjectNotExistException;
import com.peoit.honeycomb.domain.exception.UserNotExistException;
import com.peoit.honeycomb.domain.repository.HibernateEntityRepository;
import com.peoit.honeycomb.dto.CommentsDto;

/**
 * 发布讨论 ApplicaitonImpl
 * 
 * @author shisheng.zheng
 *
 */
@Service
public class CommentsApplicationImpl extends HibernateEntityRepository implements CommentsApplication {

	/**
	 * 发布讨论
	 */
	@Override
	@Transactional
	public void publishComment(String projectId, String discussantId, String content) {
		User discussant = find(User.class, discussantId);
		if (discussant == null) {
			throw new UserNotExistException();
		}
		HoneycombProject project = find(HoneycombProject.class, projectId);
		if (project == null) {
			throw new ProjectNotExistException();
		}
		Comments comment = new Comments();
		comment.setDiscussant(discussant);
		comment.setProject(project);
		comment.setComments(content);
		this.create(comment);
	}

	@Override
	public List<CommentsDto> getProjectComments(String projectId) {
		String whereSql = " project.id = ? order by createTime";
		Object[] queryParams = { projectId };
		List<Comments> comments = queryByWhereList(Comments.class, whereSql, queryParams);
		List<CommentsDto> result = new ArrayList<CommentsDto>();
		for (Comments comment : comments) {
			result.add(CommentsDto.toDto(comment));
		}
		return result;
	}

}
